package com.effvi.neo4j.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.NotFoundException;
import org.neo4j.graphdb.Transaction;

import com.effvi.neo4j.common.Report;
import com.effvi.neo4j.service.ImportService;
import com.effvi.neo4j.service.ReporterSerivce;
import com.effvi.neo4j.type.RelationshipTypes;

public class ImportServiceImpl implements ImportService{
	private static String ID = "id";
	@Override
	public void importRelationships(File file, GraphDatabaseService db) {
		registerShutdownHook(db);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		Report report = ReporterSerivce.createReporter("关系导入");
		report.start();
		if(reader!=null){
			boolean hasData = true;
			int pageSize = 20000;
			int pageNo = 1;
			int lineNo = 0;
			int total = 0;
			while(hasData){
				List<String> saveList = null;
				String data = null;
				lineNo = 0;
				try {
					while((data = reader.readLine()) != null && lineNo < pageSize){
						if(saveList == null){
							saveList = new ArrayList<String>();
						}
						saveList.add(data);
						lineNo++;
					}
					if(saveList==null){
						break;
					}else{
						if(saveList.size() < pageSize){
							hasData = false;
						}
					}
					Transaction tx = db.beginTx();
					try {
						for(int i = 0;i < saveList.size();i++){
							total++;
							System.out.println("正在导入第 " + total +" 条关系!");
							String line = saveList.get(i);
							if(!"".equals(line)){
								String[] element = line.split(",");
								long leftId = Long.valueOf(element[0]);
								long rightId = Long.valueOf(element[1]);
//		        		System.out.println(data);
								Node leftNode = null;
								try {
									leftNode = db.getNodeById(leftId);
								} catch (NotFoundException e) {
									e = null;
								}
								Node rightNode = null;
								try {
									rightNode = db.getNodeById(rightId);
								} catch (NotFoundException e) {
									e = null;
								}
								if(leftNode == null){
									leftNode = db.createNode();
									leftNode.setProperty(ID, leftId);
//		        				leftNode.setProperty(NAME, split[2]);
								}
								if(rightNode == null){
									rightNode = db.createNode();
									rightNode.setProperty(ID, rightId);
//		        				rightNode.setProperty(NAME, split[3]);
								}
								rightNode.createRelationshipTo(leftNode, RelationshipTypes.FOLLOW);
//								leftNode.createRelationshipTo(rightNode, RelationshipTypes.FANS);
								tx.success();
							}
						}
					}finally{
//						System.out.println("提交关系-->"+pageNo);
						tx.finish();
						pageNo++;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		report.end().report();
		db.shutdown();
	}
	
	private static void registerShutdownHook(final GraphDatabaseService graphDb) {  
        // Registers a shutdown hook for the Neo4j instance so that it  
        // shuts down nicely when the VM exits (even if you "Ctrl-C" the  
        // running example before it's completed)  
        Runtime.getRuntime().addShutdownHook(new Thread() {  
            @Override  
            public void run() {  
                graphDb.shutdown();  
            }  
        });  
    }
}
